<?php

namespace libs;

use libs\registry as Registry;
use libs\stringMethods as StringMethods;

Class Model
{
    
    protected $connection;
    public $data = array();
    
    public function __construct($options) 
    {
        $this->data['tabel'] = get_class($this);
        $this->connection = Registry::get('database');
        
        foreach($options as $property => $value)
        {
            if(property_exists($this, $property))
            {
                $this->data[$property] = $value;
            }
        }
        
    }
    
    public function save($data = array())
    {   
        $tabela = StringMethods::plural($this->data['tabel']);
        unset($this->data['tabel']);
        
        if($this->data['id'])
        {
            $data['id'] = $this->data['id'];
            
            $this->connection->update($tabela,$data,
                                array('id'=>$this->data['id']));
            return true;
        }
        
        $this->connection->insert($tabela,$this->data);
        
        return true;
    }
    
    public function find()
    {
        $tabela = StringMethods::plural($this->data['tabel']);
        
        unset($this->data['tabel']);
        
        $result = $this->connection->get_where($tabela,$this->data);
        
        if($result == null)
        {
            return false;
        }
        
        foreach($result as $user)
        {
            $data[] = new $this($user);
        }
        
        return $data;
    }
}